package zcw.com.lib_leet_code;

import zcw.com.lib_leet_code.bean.ListNode;
import zcw.com.lib_leet_code.util.Util;

/**
 * Created by 朱城委 on 2021/7/27.<br><br>
 *
 * 环形链表 II
 */
public class Topic142 {
    public static void main(String[] args) {
        Topic142 instance = new Topic142();

        int[] array = new int[] {3,2,0,-4};
        ListNode head = Util.createList(array);
        ListNode node1 = Util.getNode(head, -4);
        ListNode node2 = Util.getNode(head, 2);
        node1.next = node2;
        System.out.println(instance.detectCycle(head).val);
    }

    public ListNode detectCycle(ListNode head) {
        ListNode slow = head;
        ListNode fast = head;

        while (fast != null) {
            slow = slow.next;
            fast = fast.next;

            if(fast == null) {
                return null;
            }

            fast = fast.next;

            if(fast == slow) {
                slow = head;
                while (slow != fast) {
                    slow = slow.next;
                    fast = fast.next;
                }

                return slow;
            }
        }

        return null;
    }
}
